package com.bw.db.room

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Room
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.bw.db.room.migrations.UserInfoColumnDeleteMigration
import java.sql.SQLException

object RoomDBUtils {
    private const val parkDataBaseName = "app_db"
    private lateinit var roomDb:AppDataBase
    private val MIGRATION_1_2 = object :Migration(2,3){
        override fun migrate(database: SupportSQLiteDatabase) {
            try {
                //使用SQL语句来升级数据库
                val renameTableSql = "ALTER TABLE user_info_table RENAME To user_info"
                database.execSQL(renameTableSql)
            }catch (e:SQLException){
                e.printStackTrace()
            }
        }
    }

    //自动升级策略
    private val AUTO_MIGRATION_SPEC =object : AutoMigrationSpec {
        override fun onPostMigrate(db: SupportSQLiteDatabase) {
            super.onPostMigrate(db)
            try {
                //使用SQL语句来升级数据库
                val renameTableSql = "ALTER TABLE user_info_table RENAME To user_info"
                db.execSQL(renameTableSql)
            }catch (e:SQLException){
                e.printStackTrace()
            }
        }
    }


    /**
     * 初始化
     */
    fun initRoom(ctx:Context){
        roomDb = Room.databaseBuilder(ctx, AppDataBase::class.java, parkDataBaseName)
//            .addMigrations( MIGRATION_1_2)
//            .addAutoMigrationSpec(AUTO_MIGRATION_SPEC)
            .build()
    }


    /**
     * 获取操作Dao
     */
    fun getDataBase():AppDataBase{
        if (roomDb == null){
            throw RuntimeException("请先初始化数据库")
        }
        return roomDb
    }
}